package ccxz.biz.application.util;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class WeightRandomStrategyUtil {

    public static String getNum() {
        List<WeightRandomItem> list = new ArrayList<>();
        list.add(WeightRandomItem.builder().num("3").weight(10).build());
        list.add(WeightRandomItem.builder().num("5").weight(10).build());
        list.add(WeightRandomItem.builder().num("10").weight(10).build());
        list.add(WeightRandomItem.builder().num("15").weight(10).build());

        list.add(WeightRandomItem.builder().num("6").weight(100).build());
        list.add(WeightRandomItem.builder().num("9").weight(100).build());
        list.add(WeightRandomItem.builder().num("12").weight(100).build());

        int weightSum = list.stream().mapToInt(WeightRandomItem::getWeight).sum();
        String result = null;
        Random random = new Random();
        int n = random.nextInt(weightSum); // n in [0, weightSum)
        int m = 0; // 权重区间边界
        for (WeightRandomItem wc : list) {
            if (m <= n && n < m + wc.getWeight()) {
                result = wc.getNum();
                break;
            }
            m += wc.getWeight();
        }
        return result;
    }


    @Data
    @Builder
    @NoArgsConstructor
    @AllArgsConstructor
    public static class WeightRandomItem {
        private String num;
        private int weight;
    }

}